package com.shine.chemicalWholeProcessSystem.http;

import android.text.TextUtils;

import com.shine.chemicalWholeProcessSystem.app.BaseApplication;

import java.io.File;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ConnectionPool;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.internal.platform.Platform;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * Created by goldze on 2017/5/10.
 * RetrofitClient封装单例类, 实现网络请求
 */
public class RetrofitClientNew {
    // Fields from build type: debug
    public static final String API_KEY = "ABCXYZ123TEST";
    //    public static final String BASE_URL = "https://cdn.engchat.vip/svr/";

//        public static final String BASE_URL = "http://a.quyb.net/apis/";
        public static final String BASE_URL = "http://172.16.19.203:42850/";
    public static final String BASE_IMG_URL = "http://172.16.19.203:42850/";

    public static final String WX_APP_ID = "wxf51a229c8cdec856";

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    //超时时间
    private static final int DEFAULT_TIMEOUT = 30;
    //缓存时间
    private static final int CACHE_TIMEOUT = 10 * 1024 * 1024;
    //服务端根路径
    private static String baseUrl = BASE_URL;

//    private static Context mContext = Utils.getContext();

    private static OkHttpClient okHttpClient;
    private static Retrofit retrofit;

//    private Cache cache = null;
//    private File httpCacheDirectory;

    private static class SingletonHolder {
        private static RetrofitClientNew INSTANCE = new RetrofitClientNew();
    }

    public static RetrofitClientNew getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private RetrofitClientNew() {
        this(baseUrl, null);
    }

    private RetrofitClientNew(String url, Map<String, String> headers) {

        if (TextUtils.isEmpty(url)) {
            url = baseUrl;
        }

//        if (httpCacheDirectory == null) {
//            httpCacheDirectory = new File(mContext.getCacheDir(), "engchina_cache");
//        }
//
//        try {
//            if (cache == null) {
//                cache = new Cache(httpCacheDirectory, CACHE_TIMEOUT);
//            }
//        } catch (Exception e) {
//            KLog.e("Could not create http cache", e);
//        }
        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory();
        okHttpClient = new OkHttpClient.Builder()
//                .cookieJar(new CookieJarImpl(new PersistentCookieStore(mContext)))
//                .cache(cache)
//                .addInterceptor(new Interceptor() {
//                    @Override
//                    public Response intercept(Chain chain) throws IOException {
//                        Request request = chain.request().newBuilder()
//                                .addHeader("Authorization", SPUtils.getInstance().getString(Constants.SP_TOKEN))
////                                .addHeader("Cookie", "currApiUser=" + SPUtils.getInstance().getString(Constants.SP_COOKIE))
//                                .build();
//                        return chain.proceed(request);
//                    }
//                })
//                .addInterceptor(new BaseInterceptor(headers))
                .addInterceptor(new CacheInterceptor(BaseApplication.getContext()))
                .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
                .addInterceptor(new LoggingInterceptor
                                .Builder()//构建者模式
                                .loggable(true) //是否开启日志打印
                                .setLevel(Level.BASIC) //打印的等级
                                .log(Platform.INFO) // 打印类型
                                .request("Request") // request的Tag
                                .response("Response")// Response的Tag
//                        .addHeader("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 ") // 添加请求头token
                                .build()
                )
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool(8, 15, TimeUnit.SECONDS))
                // 这里你可以根据自己的机型设置同时连接的个数和时间，我这里8个，和每个保持时间为10s
                .build();


        retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(url)
                .build();
    }

    /**
     * create you ApiService
     * Create an implementation of the API endpoints defined by the {@code service} interface.
     */
    public <T> T create(final Class<T> service) {
        if (service == null) {
            throw new RuntimeException("Api service is null!");
        }
        return retrofit.create(service);
    }

    /**
     * /**
     * execute your customer API
     * For example:
     * MyApiService service =
     * RetrofitClient.getInstance(MainActivity.this).create(MyApiService.class);
     * <p>
     * RetrofitClient.getInstance(MainActivity.this)
     * .execute(service.lgon("name", "password"), subscriber)
     * * @param subscriber
     */

    public static <T> T execute(Observable<T> observable, Observer<T> subscriber) {
        observable.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);

        return null;
    }

    public Observable<ECHttpResponse<FileBean>> uploadFile(File file, String type) {

        String fileName = file.getName();

        RequestBody requestFile = new MultipartBody.Builder().setType(MultipartBody.FORM)
//                .addFormDataPart("token", AccountHelper.getToken())
//                .addFormDataPart("uid", AccountHelper.getUid())
                .addFormDataPart("tpe", type)
                .addFormDataPart("ext", fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()))
                .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file))
                .build();

        return create(Service.class)
                .upLoad(requestFile)//请求与View周期同步
                .compose(RxUtils.<ECHttpResponse<FileBean>>schedulersTransformer())//线程调度
                .compose(RxUtils.<ECHttpResponse<FileBean>>exceptionTransformer());// 网络错误的异常转换
    }

//    public Observable<ECHttpResponse<BaseReturn>> getTimestamp() {
//
//        String url = "http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp";
//        return create(Service.class)
//                .getTimestamp(url)//请求与View周期同步
//                .compose(RxUtils.schedulersTransformer())//线程调度
//                .compose(RxUtils.exceptionTransformer());// 网络错误的异常转换
//    }
}
